/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JTreeFromXMLFile.java
 *
 * Created on 10-06-2009, 14:28:32
 */

package doanlythuyet_javaoutlook.MyUserControl;

import BUS.MyContactBUS;
import DTO.MyContactDTO;
import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile;
import doanlythuyet_javaoutlook.MyEmum.JEnum_ContactGroupBy;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.*;
import java.io.IOException;
//import javax.swing.;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.Enumeration;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.MouseInputListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;

import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;

/**
 *
 * @author ShineShiao
 */
public class JPanel_HienThiContact extends javax.swing.JPanel {
    private boolean m_chiDoc;
    private final JPopupMenu m_popupMenu;
    private JEnum_ContactGroupBy m_ThuocTinhGroupBy;// = "C:\\Documents and Settings\\Administrator\\Desktop\\JavaMail\\ 0512324-0512328-0512333-mailclient\\DoAnLyThuyet_JavaOutLook\\src\\Database\\XML_ThuMucNguoiDung.xml";
    /** Creates new form JTreeFromXMLFile */
    public void expandTree (TreePath path){
        jTreeThuMucNguoiDung.expandPath(path);
    }
    // If expand is true, expands all nodes in the tree.
    // Otherwise, collapses all nodes in the tree.
    public static void expandAll(JTree tree, boolean expand) {
        TreeNode root = (TreeNode)tree.getModel().getRoot();

        // Traverse tree from root
        expandAll(tree, new TreePath(root), expand);
    }
    private static void expandAll(JTree tree, TreePath parent, boolean expand) {
        // Traverse children
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode)e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(tree, path, expand);
            }
        }

        // Expansion or collapse must be done bottom-up
        if (expand) {
            tree.expandPath(parent);
        } else {
            tree.collapsePath(parent);
        }
    }
    public JPanel_HienThiContact(JEnum_ContactGroupBy thuocTinhGroupBy, Boolean chiDoc) throws SQLException, SAXException, ParserConfigurationException {
        m_chiDoc = chiDoc;
        m_ThuocTinhGroupBy = thuocTinhGroupBy;
        m_popupMenu = new JPopupMenu();
        if (!chiDoc){
            String cacHanhViThayDoiCauTruc[] = {"Thêm mới", "Xóa", "Đổi Tên"};

            for (String HanhVi : cacHanhViThayDoiCauTruc)
            {
                JMenuItem menuItem = new JMenuItem(HanhVi);
                menuItem.addMouseListener(new PopupMenu_MouseListerner_MyCayHienThiThuMuc(menuItem.getText()));
                m_popupMenu.add(menuItem);
            }
            m_popupMenu.addSeparator();
        }
        String cacHanhViKhongThayDoiCauTruc[] = {"Đánh dấu đã đọc", "Đánh dấu chưa đọc", "Gỡ dấu"};

        for (String HanhVi : cacHanhViKhongThayDoiCauTruc)
        {
            JMenuItem menuItem = new JMenuItem(HanhVi);
            menuItem.addMouseListener(new PopupMenu_MouseListerner_MyCayHienThiThuMuc(menuItem.getText()));
            m_popupMenu.add(menuItem);
        }
        initComponents();
        try {
            thayDoiIconCuaTree();
            MyContactBUS contactBUS = new MyContactBUS();
            ArrayList<MyContactDTO> cacContactDTO= contactBUS.layTatCaContact();
            TaoCay(cacContactDTO);
            //expandTree(new TreePath(jTreeThuMucNguoiDung.getModel().getRoot()));
            expandAll(jTreeThuMucNguoiDung, true);
            
            
        } catch (IOException ex) {
            Logger.getLogger(JTreeFromXMLFile.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Tao cay thu muc tu file XML loi: " + ex.getMessage());
        }

        jTreeThuMucNguoiDung.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (jTreeThuMucNguoiDung.getSelectionPath() == null)
                    return;
                String strPath = StringPathFromTreePath(jTreeThuMucNguoiDung.getSelectionPath());
                getM_popupMenu().setToolTipText(strPath);
                if (e.getButton() == MouseEvent.BUTTON3) {
                    getM_popupMenu().show(e.getComponent(), e.getX(), e.getY());
                    //return;
                }
            }

            public void mousePressed(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            public void mouseReleased(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            public void mouseEntered(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            public void mouseExited(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        });
    }

    public static TreePath TreePathFromStringPath (String stringPath){
        String cacPath[] = stringPath.split("\\\\");
        MutableTreeNode cacNode[] = new MutableTreeNode[cacPath.length];
        for (int i = 0; i < cacPath.length; i++)
            cacNode[i] = new DefaultMutableTreeNode(cacPath[i]);
        return new TreePath(cacNode);
    }

    public static String StringPathFromTreePath (TreePath treePath){
        String Kq = "";
        Object cacNode[] = treePath.getPath();
        for (int i = 0; i < cacNode.length; i++)
            Kq += ((DefaultMutableTreeNode)cacNode[i]).getUserObject().toString() + "\\";
        return Kq;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTreeThuMucNguoiDung = new javax.swing.JTree();

        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTreeThuMucNguoiDung.setName("jTreeThuMucNguoiDung"); // NOI18N
        jTreeThuMucNguoiDung.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreeThuMucNguoiDungValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTreeThuMucNguoiDung);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTreeThuMucNguoiDungValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeThuMucNguoiDungValueChanged
        // TODO add your handling code here:
        String strPath = StringPathFromTreePath(jTreeThuMucNguoiDung.getSelectionPath());
        initEvent_ClickChuotVaoCayDuyetFile(strPath);
    }//GEN-LAST:event_jTreeThuMucNguoiDungValueChanged
    public void TaoCay(ArrayList<MyContactDTO> cacContactDTO) throws SAXException, IOException, ParserConfigurationException{

        DefaultTreeModel model = (DefaultTreeModel)getJTreeThuMucNguoiDung().getModel();
        MutableTreeNode newNode = new DefaultMutableTreeNode("Contacts");
        model.setRoot(newNode);

        String strGroupHienTai = "";
        String strGroupCuaPhanTuTiepTheo = "";
        for (MyContactDTO contactDTO : cacContactDTO){
            strGroupCuaPhanTuTiepTheo = layGroupCuaPhanTuTiepTheo(contactDTO);
            if (!strGroupCuaPhanTuTiepTheo.equals(strGroupHienTai)){
                strGroupHienTai = strGroupCuaPhanTuTiepTheo;
            }
        }

    }
    public void ThemXMLElementVaoTree(DefaultTreeModel model,Element ele,MutableTreeNode nodeCha){
        MutableTreeNode newNode = new DefaultMutableTreeNode(ele.getAttribute("name"));
        model.insertNodeInto(newNode, nodeCha, nodeCha.getChildCount());
              for (int i =0;i<ele.getChildNodes().getLength();i++){
                  ThemXMLElementVaoTree(model, (Element)ele.getChildNodes().item(i), newNode);
          }
    }

    /** Thay đổi icon của cây
     *
     *
     */
    public void thayDoiIconCuaTree(){
        // Retrieve the three icons
        Icon leafIcon = new ImageIcon("leaf.gif");
        Icon openIcon = new ImageIcon("open.gif");
        Icon closedIcon = new ImageIcon("closed.gif");


        // Update only one tree instance
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTreeThuMucNguoiDung.getCellRenderer();
        renderer.setLeafIcon(leafIcon);
        renderer.setClosedIcon(closedIcon);
        renderer.setOpenIcon(openIcon);

        // Remove the icons
        renderer.setLeafIcon(null);
        renderer.setClosedIcon(null);
        renderer.setOpenIcon(null);

        // Change defaults so that all new tree components will have new icons
        UIManager.put("Tree.leafIcon", leafIcon);
        UIManager.put("Tree.openIcon", openIcon);
        UIManager.put("Tree.closedIcon", closedIcon);

        // Create tree with new icons
        //setJTreeThuMucNguoiDung(tree);

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTreeThuMucNguoiDung;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the jTreeThuMucNguoiDung
     */
    public javax.swing.JTree getJTreeThuMucNguoiDung() {
        return jTreeThuMucNguoiDung;
    }

    /**
     * @param jTreeThuMucNguoiDung the jTreeThuMucNguoiDung to set
     */
    public void setJTreeThuMucNguoiDung(javax.swing.JTree jTreeThuMucNguoiDung) {
        this.jTreeThuMucNguoiDung = jTreeThuMucNguoiDung;
    }
    //<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien">
    //Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
    //http://www.exampledepot.com/egs/java.util/CustEvent.html
    // Tạo một listener list
    protected javax.swing.event.EventListenerList listenerList =
            new javax.swing.event.EventListenerList();

    /**
     * Phát sinh sử kiện click chuột vào tree
     * @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn)
     */
    // This private class is used to fire MyEvents
    void initEvent_ClickChuotVaoCayDuyetFile(String evt) {
        Object[] listeners = listenerList.getListenerList();
        // Each listener occupies two elements - the first is the listener class
        // and the second is the listener instance
        for (int i = 0; i < listeners.length; i += 2) {
            if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) {
                ((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt);
            }
        }
    }

    /**
     * Đăng ký sự kiện cho classes
     * @param listener  Sự kiện cần đăng ký
     */
    public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
        listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
    }

    /**
     * Gỡ bỏ sự kiện khỏi classes
     * @param listener  Sự kiện cần gỡ bỏ
     */
    public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
        listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
    }

    /**
     * @return the m_popupMenu
     */
    public JPopupMenu getM_popupMenu() {
        return m_popupMenu;
    }

    private String layGroupCuaPhanTuTiepTheo(MyContactDTO contactDTO) {
        String strGroupCuaPhanTuTiepTheo = "";
        switch (m_ThuocTinhGroupBy) {
            case Adress:
                {
                    strGroupCuaPhanTuTiepTheo = contactDTO.getM_Email();
                    break;
                }
            case Company:
                {
                    strGroupCuaPhanTuTiepTheo = contactDTO.getM_CongTy();
                    break;
                }
            default:
                {
                    break;
                }
        }
        return strGroupCuaPhanTuTiepTheo;
    }
    //</editor-fold>
}
